<template>
	<view>
		<!-- 答题组件 -->
		<kz-question mode="VIEW" :title="cateName" :questions="questions" :questionCount="questionCount"
			:pageCount="pageCount" :currentPage="currentPage" :viewMode="mode" :trainType="trainType" 
			@loadQuestion="getQuestion" @nextQuestion="handleNextQuestion" @refresh="refreshPage">
		</kz-question>

		<!-- toast提示 -->
		<tui-toast ref="toast"></tui-toast>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cateId: 0,
				cateName: '',
				questions: [],
				questionCount: 0,
				pageCount: 20,
				currentPage: 0,
				lastPage: 0,
				mode: 'normal',
				trainType: 'normal',
				// 支付检查相关
				needSendProgress: false,
				progressCateId: 0,
			}
		},
		onLoad(e) {
			this.cateId = e.cateId
			this.cateName = e?.cateName || '背题模式'
			this.mode = e.mode
			this.trainType = e?.trainType || 'normal'

			// 设置导航栏标题
			uni.setNavigationBarTitle({
				title: this.cateName
			})

			console.log('mode', this.mode, 'trainType', this.trainType)
			
			// 检查支付状态
			this.checkPay()
			
			// 开始加载数据
			if (this.mode === 'memory') {
				// 记忆模式 - 检查记忆位置
				const cacheKey = 'view' + '-' + this.cateId
				const memoryData = this.utils.getData(cacheKey)
				if (memoryData && memoryData.memory_index) {
					// 获取记忆位置并计算需要加载的数据量
					const memoryIndex = memoryData.memory_index
					const neededPage = Math.ceil(memoryIndex / this.pageCount)
					const totalCount = neededPage * this.pageCount
					this.getQuestion(1, totalCount)
				} else {
					// 没有记忆数据，只加载第一页
					this.getQuestion()
				}
			} else {
				// 普通模式，只加载第一页
				this.getQuestion()
			}
		},
		methods: {
			// 检查支付状态
			checkPay() {
				this.http('cate/checkPay', {
					cate_id: this.cateId
				}).then(res => {
					console.log('checkPay response:', res)
					if (res && res.code === 1 && res.data) {
						const { price, status, cate } = res.data
						// 当 price > 0 并且 status = 1 时，需要发送进度
						if (parseFloat(price) > 0 && status === 1 && cate && cate.id) {
							this.needSendProgress = true
							this.progressCateId = cate.id
							console.log('需要发送进度，cate_id:', this.progressCateId)
						}
					}
				}).catch(err => {
					console.error('checkPay error:', err)
				})
			},
			
			// 刷新页面
			refreshPage() {
				// 清空当前数据
				this.questions = []
				this.currentPage = 0
				// 重新加载第一页
				this.getQuestion()
			},
			
			// 处理下一题事件 - 参考train.vue的实现
			handleNextQuestion() {
				console.log('handleNextQuestion called, needSendProgress:', this.needSendProgress)
				
				// 发送进度（如果需要）
				if (this.needSendProgress) {
					this.sendProgress()
				}
				
				// 如果接近当前页的末尾，预加载下一页
				if (this.currentPage < this.lastPage && 
					this.questions.length - (this.currentPage * this.pageCount) < 5) {
					this.getQuestion(this.currentPage + 1)
				}
			},
			
			// 发送进度
			sendProgress() {
				if (!this.progressCateId) {
					console.warn('progressCateId is empty')
					return
				}
				
				this.http('/Grade/progress', {
					cate_id: this.progressCateId
				}).then(res => {
					console.log('sendProgress response:', res)
				}).catch(err => {
					console.error('sendProgress error:', err)
				})
			},
			
			// 获取试题
			getQuestion(page = 1, count = 20, callback = null) {
				// 如果count是函数，说明调用时将回调作为第二个参数传入
				if (typeof count === 'function') {
					callback = count
					count = 20
				}
				
				// 避免重复获取
				if (page <= this.currentPage || (this.lastPage && page > this.lastPage)) {
					if (typeof callback === 'function') {
						callback()
					}
					return
				}

				// 请求参数
				let params = {
					page: page,
					page_count: count,
					cate_id: this.cateId,
					mode: this.mode,
					type: 'train'
				}
				
				// 发送请求
				this.http('question/train', params, 'post', false).then(res => {
					
					if (res.code == 1) {
						// 更新分页信息
						this.questionCount = res.data.total
						this.lastPage = Math.ceil(res.data.total / this.pageCount)
						this.currentPage = page
						
						// 处理数据
						if (res.data.data && res.data.data.length > 0) {
							if (page === 1) {
								this.questions = res.data.data
							} else {
								this.questions = this.questions.concat(res.data.data)
							}
						}

						// 积分提示
						let point = res.data.point
						if (point?.get_point > 0) {
							this.$refs.toast.show({
								title: "积分+" + point.get_point,
								content: point.type,
								imgUrl: "/static/toast/info-circle.png",
								icon: true,
								duration: 4000
							})
						}
					} else {
						if (res.data && res.data.need_open_member) {
							uni.showModal({
								title: '提示',
								content: res.msg,
								confirmText: '前往开通',
								success: (res) => {
									if (res.confirm) {
										this.utils.goto('/pages/user/member-center?from_train=1')
									} else if (res.cancel) {
										this.utils.goback()
									}
								}
							})
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					}
					
					// 执行回调 - 添加延时确保数据同步到子组件
					if (typeof callback === 'function') {
						setTimeout(() => {
							callback()
						}, 200)
					}
				}).catch(err => {
					
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
					
					// 即使出错也要执行回调
					if (typeof callback === 'function') {
						setTimeout(() => {
							callback()
						}, 100)
					}
				})
			}
		}
	}
</script>

<style>

</style>
